import express from 'express';
import personService from '../person.service.backend.js';
import Person from '../models/Person.js';

const router = express.Router();

// Middleware for handling async route handlers
const asyncHandler = fn => (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(next);
};

// GET all persons
router.get('/persons', asyncHandler(async (req, res) => {
    // In a real app, you might get familyTreeId from req.query or from the authenticated user's session
    const persons = await personService.getAllPersons(req.query.familyTreeId);
    res.json(persons);
}));

// 获取已删除成员（回收站）- 必须在 /persons/:id 之前定义
router.get('/persons/deleted', asyncHandler(async (req, res) => {
    const Person = (await import('../models/Person.js')).default;
    
    // 使用原始SQL查询确保能正确获取软删除的成员，只返回基本信息
    const deletedPersons = await Person.sequelize.query(
      'SELECT person_id as id, family_tree_id as "familyTreeId", name, gender, birth_date as "birthDate", generation, death_date as "deathDate", occupation, education, address, marital_status as "maritalStatus", phone, email, description, photos, avatar, created_at as "createdAt", updated_at as "updatedAt", deleted_at as "deletedAt" FROM persons WHERE deleted_at IS NOT NULL ORDER BY person_id ASC',
      { 
        type: Person.sequelize.QueryTypes.SELECT
      }
    );
    
    console.log(`【调试】回收站查询到 ${deletedPersons.length} 个已删除成员`);
    res.json(deletedPersons);
}));

// GET a single person by ID
router.get('/persons/:id', asyncHandler(async (req, res) => {
    // 只允许数字id
    if (isNaN(Number(req.params.id))) {
        return res.status(400).json({ error: '成员ID无效' });
    }
    const person = await personService.getPersonDetail(req.params.id);
    if (person) {
        res.json(person);
    } else {
        res.status(404).json({ error: 'Person not found' });
    }
}));

// 获取亲属关系
router.get('/persons/:id/relatives', asyncHandler(async (req, res) => {
    const relatives = await personService.getRelatives(req.params.id);
    res.json(relatives);
}));

// POST (create) a new person
router.post('/persons', asyncHandler(async (req, res) => {
    const newPerson = await personService.createPerson(req.body);
    res.status(201).json(newPerson);
}));

// PUT (update) a person
router.put('/persons/:id', asyncHandler(async (req, res) => {
    const updatedPerson = await personService.updatePerson(req.params.id, req.body);
    res.json(updatedPerson);
}));

// DELETE a person
router.delete('/persons/:id', asyncHandler(async (req, res) => {
    await personService.deletePerson(req.params.id);
    res.status(204).send();
}));

// 更新人员照片
router.put('/persons/:id/photos', asyncHandler(async (req, res) => {
  const { id } = req.params;
  const { photos } = req.body;
  
  const person = await Person.findByPk(id);
  if (!person) {
    return res.status(404).json({ error: '人员不存在' });
  }
  
  person.photos = photos;
  await person.save();
  
  res.json({ success: true, message: '照片更新成功', photos: person.photos });
}));

// 获取家谱树结构（实际就是所有成员）
router.get('/persons/tree', asyncHandler(async (req, res) => {
    const persons = await personService.getAllPersons(req.query.familyTreeId);
    res.json(persons);
}));

// 登录接口
router.post('/login', asyncHandler(async (req, res) => {
    const { username, password } = req.body;
    console.log('收到登录请求:', username, password); // 打印收到的用户名和密码
    if (!username || !password) {
        console.log('用户名或密码为空');
        return res.status(400).json({ error: '用户名和密码不能为空' });
    }
    const User = (await import('../models/User.js')).default;
    const user = await User.findOne({ where: { username } });
    if (!user) {
        console.log('用户不存在:', username);
        return res.status(401).json({ error: '用户不存在' });
    }
    const isValid = await user.validPassword(password);
    if (!isValid) {
        console.log('密码错误:', username, password);
        return res.status(401).json({ error: '密码错误' });
    }
    console.log('登录成功:', username);
    res.json({ id: user.id, username: user.username, role: user.role });
}));

// 恢复已删除成员
router.post('/persons/:id/restore', asyncHandler(async (req, res) => {
    const Person = (await import('../models/Person.js')).default;
    
    // 使用原始SQL查询找到已删除的成员
    const deletedPerson = await Person.sequelize.query(
      'SELECT * FROM persons WHERE person_id = ? AND deleted_at IS NOT NULL',
      { 
        type: Person.sequelize.QueryTypes.SELECT,
        replacements: [req.params.id]
      }
    );
    
    if (deletedPerson.length === 0) {
        return res.status(404).json({ error: '成员不存在或未被删除' });
    }
    
    // 使用原始SQL恢复成员
    await Person.sequelize.query(
      'UPDATE persons SET deleted_at = NULL WHERE person_id = ?',
      { 
        type: Person.sequelize.QueryTypes.UPDATE,
        replacements: [req.params.id]
      }
    );
    
    console.log(`【调试】已恢复成员 ID: ${req.params.id}`);
    res.json({ success: true, message: '成员已恢复' });
}));

// 全局错误处理中间件
router.use((error, req, res, next) => {
    console.error('【全局错误】', {
        url: req.url,
        method: req.method,
        error: error.message,
        stack: error.stack
    });
    
    res.status(500).json({
        error: 'Internal Server Error',
        message: error.message,
        url: req.url
    });
});

export default router; 